package com.example.springblog.service;

import com.example.springblog.constant.Constants;
import com.example.springblog.mapper.BlogMapper;
import com.example.springblog.mapper.UserMapper;
import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.UserInfo;
import com.example.springblog.model.UserVO;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;

    public UserInfo selectByName(String userName) {
        return userMapper.selectByName(userName);
    }
    public String isCorrectCaptcha(String captcha, HttpSession session) {
        // 获取存储的验证码和生成时间
        String code = (String) session.getAttribute(Constants.CAPTCHA_KEY);
        Date createTime = (Date) session.getAttribute(Constants.CAPTCHA_DATE);
        // 判断验证码是否正确（验证码一般忽略大小写）
        if(captcha.equalsIgnoreCase(code)) {
            // 判断验证码是否超时
            if(createTime == null || System.currentTimeMillis() - createTime.getTime() < Constants.EXPIRATION_TIME) {
                return null;
            }
            return "验证码已超时";
        }
        return "验证码错误";
    }

    public int insertUser(String userName, String password) {
        return userMapper.insertUser(userName, password);
    }

    public UserVO getUserInfo(Integer userId) {
        UserInfo userInfo =  userMapper.selectById(userId);
        return new UserVO(userInfo.getUserName(), userInfo.getGithubUrl());
    }

    public UserVO getUserInfoByBlogId(Integer blogId) {
        // 获取博客相关信息
        BlogInfo blogInfo = blogMapper.selectById(blogId);
        if(blogInfo != null && blogInfo.getUserId() > 0) {
            UserInfo userInfo =  userMapper.selectById(blogInfo.getUserId());
            return new UserVO(userInfo.getUserName(), userInfo.getGithubUrl());
        }
        return null;
    }
}
